package cn.edu.sgu.www.mhxysy.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ip地址工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class IpUtils {

    /**
     * 获取客户端IP
     * @return String
     */
    public static String getIp() {
        // 获取HttpServletRequest对象
        HttpServletRequest request = HttpUtils.getRequest();
        // 客户端IP
        String clientIp = request.getHeader("x-forwarded-for");

        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_CLIENT_IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Real-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }

        return clientIp;
    }

    /**
     * 获取浏览器类型
     * @return String 浏览器类型
     */
    public static String getBrowserType() {
        HttpServletRequest request = HttpUtils.getRequest();
        String type = "其它";
        String browserName = request.getHeader("USER-AGENT").toLowerCase();

        if (browserName.indexOf("msie") > 0) {
            type = "IE";
        } else if (browserName.indexOf("firefox") > 0) {
            type = "Firefox";
        } else if (browserName.indexOf("chrome") > 0) {
            type = "Chrome";
        } else if (browserName.indexOf("opera") > 0) {
            type = "Opera";
        } else if (browserName.indexOf("gecko") > 0 && browserName.indexOf("rv:11") > 0) {
            type = "IE11";
        }

        return type;
    }

    /**
     * 获取本机主机名称
     */
    public static String getLocalHostName() {
        InetAddress inetAddress = null;

        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return inetAddress == null ? null : inetAddress.getHostName();
    }

    /**
     * 获取本机IP地址
     */
    public static String getLocalHostAddress() {
        InetAddress inetAddress = null;

        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return inetAddress == null ? null : inetAddress.getHostAddress();
    }

}